import 'package:awak/common/routers/router_names.dart';
import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/values/svg.dart';
import 'package:awak/common/values/images.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:awak/bloc/auth/auth_bloc.dart';
import 'package:awak/bloc/auth/auth_event.dart';
import 'package:awak/bloc/auth/auth_state.dart';
import 'package:awak/common/models/user.dart';
import 'package:awak/common/models/chat.dart';
import 'package:awak/common/utils/util_dialog.dart';

class MessageProfilePage extends StatefulWidget {
  const MessageProfilePage({super.key});

  @override
  State<MessageProfilePage> createState() => _MessageProfilePageState();
}

class _MessageProfilePageState extends State<MessageProfilePage> {
  int _selectedTabIndex = 0; // 0 = private letter, 1 = friend
  List<User> _chatUsers = [];
  Map<int, Chat> _latestMessages = {};
  Map<int, int> _unreadCounts = {};
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  void _loadData() {
    final currentUser = context.read<AwakBloc>().userRepository.currentUser;
    if (currentUser != null) {
      // 加载好友列表
      context.read<AwakBloc>().add(FetchFriendsEvent(currentUser.id!));
      _loadChatUsers();
    } else {
      // 如果没有当前用户，延迟重试
      Future.delayed(Duration(milliseconds: 500), () {
        if (mounted) {
          _loadData();
        }
      });
    }
  }

  Future<void> _loadChatUsers() async {
    final awakBloc = context.read<AwakBloc>();
    final currentUser = awakBloc.userRepository.currentUser;
    if (currentUser == null) return;

    try {
      // 获取所有聊天记录
      final allChats = await awakBloc.chatRepository.getAllChatsForUser(currentUser.id!);

      // 获取聊过天的用户ID
      Set<int> chatUserIds = {};
      Map<int, Chat> latestMessages = {};

      for (final chat in allChats) {
        int otherUserId = chat.sendUserId == currentUser.id ? chat.acceptUserId : chat.sendUserId;
        chatUserIds.add(otherUserId);

        // 保存最新消息
        if (!latestMessages.containsKey(otherUserId) ||
            chat.sendTime.isAfter(latestMessages[otherUserId]!.sendTime)) {
          latestMessages[otherUserId] = chat;
        }
      }

      // 获取用户信息
      List<User> chatUsers = [];
      final userRepository = awakBloc.userRepository;
      final chatRepository = awakBloc.chatRepository;

      for (int userId in chatUserIds) {
        final user = await userRepository.getUserById(userId);
        if (user != null) {
          chatUsers.add(user);
        }
      }

      // 获取未读消息数
      final unreadCounts = await chatRepository.getUnreadCountsForAllChats(currentUser.id!);

      if (!mounted) return;

      if (mounted) {
        setState(() {
          _chatUsers = chatUsers;
          _latestMessages = latestMessages;
          _unreadCounts = unreadCounts;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<AwakBloc, AwakState>(
      listener: (context, state) {
        // 监听好友相关的状态变化
        if (state is FriendRemoved) {
          // 好友删除后重新加载数据
          _loadData();
        }
      },
      child: Scaffold(
        body: Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.center,
              colors: [Color(0xFFD3F524), Colors.white],
            ),
          ),
          child: SafeArea(
            child: Column(
              children: [
                // 标题栏
                Container(
                  height: 60.h,
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: Row(
                    children: [
                      // 返回按钮
                      GestureDetector(
                        onTap: () => Beamer.of(context).beamBack(),
                        child: Icon(
                          AwakSvg.back,
                          size: 20.sp,
                          color: Colors.black,
                        ),
                      ),
                      Expanded(
                        child: Center(
                          child: Text(
                            'Information',
                            style: TextStyle(
                              fontSize: 24.sp,
                              fontWeight: FontWeight.bold,
                              color: Colors.black,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(width: 40.w),
                    ],
                  ),
                ),

                // 切换标签
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
                  child: Row(
                    children: [
                      _buildTabButton('private letter', 0),
                      SizedBox(width: 16.w),
                      _buildTabButton('friend', 1),
                    ],
                  ),
                ),

                // 内容区域
                Expanded(
                  child: _selectedTabIndex == 0 ? _buildChatList() : _buildFriendList(),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTabButton(String title, int index) {
    final isSelected = _selectedTabIndex == index;
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedTabIndex = index;
        });
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 8.h),
        decoration: BoxDecoration(
          color: isSelected ? const Color(0xFFD3F524) : Colors.white,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(
            color: Colors.black,
            width: 2.w,
          ),
        ),
        child: Text(
          title,
          style: AwakText.body14Style.copyWith(
            color: Colors.black,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
    );
  }

  Widget _buildChatList() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_chatUsers.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              AwakImages.empty,
              width: 100.w,
              height: 100.h,
            ),
            SizedBox(height: 20.h),
            Text(
              'No chat record yet',
              style: TextStyle(
                color: Colors.grey,
                fontSize: 16.sp,
              ),
            ),
          ],
        ),
      );
    }

    return ListView.builder(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      itemCount: _chatUsers.length,
      itemBuilder: (context, index) {
        final user = _chatUsers[index];
        final latestMessage = _latestMessages[user.id!];

        return GestureDetector(
          onTap: () async {
            // 跳转到聊天页面
            Beamer.of(context).beamToNamed(RouterNames.chatProfile, data: user);
            // 返回后重新加载数据以更新未读消息数
            _loadChatUsers();
          },
          child: Container(
            margin: EdgeInsets.only(bottom: 8.h),
            padding: EdgeInsets.all(12.w),
            decoration: BoxDecoration(
              color: const Color(0xFFF5F5F5),
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Row(
              children: [
                // 用户头像
                CircleAvatar(
                  radius: 24.r,
                  backgroundImage: AssetImage(user.avatar ?? ''),
                ),
                SizedBox(width: 12.w),

                // 用户信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            user.nickname ?? user.username,
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16.sp,
                              color: Colors.black,
                            ),
                          ),
                          Text(
                            latestMessage != null
                              ? '${latestMessage.sendTime.hour.toString().padLeft(2, '0')}:${latestMessage.sendTime.minute.toString().padLeft(2, '0')}'
                              : '',
                            style: TextStyle(
                              color: Colors.grey,
                              fontSize: 12.sp,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 4.h),
                      Text(
                        latestMessage?.context ?? '',
                        style: TextStyle(
                          color: Colors.grey,
                          fontSize: 14.sp,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),

                // 未读消息标识
                SizedBox(width: 8.w),
                _buildUnreadBadge(user.id!),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildFriendList() {
    return BlocBuilder<AwakBloc, AwakState>(
      builder: (context, state) {
        if (state is FriendshipLoading) {
          return const Center(child: CircularProgressIndicator());
        }

        if (state is FriendsLoaded) {
          final friends = state.friends;

          if (friends.isEmpty) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(
                    AwakImages.empty,
                    width: 100.w,
                    height: 100.h,
                  ),
                  SizedBox(height: 20.h),
                  Text(
                    'No friends yet',
                    style: TextStyle(
                      color: Colors.grey,
                      fontSize: 16.sp,
                    ),
                  ),
                ],
              ),
            );
          }

          return ListView.builder(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            itemCount: friends.length,
            itemBuilder: (context, index) {
              final friend = friends[index];

              return Container(
                margin: EdgeInsets.only(bottom: 8.h),
                padding: EdgeInsets.all(12.w),
                decoration: BoxDecoration(
                  color: Colors.transparent,
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Row(
                  children: [
                    // 好友头像
                    CircleAvatar(
                      radius: 24.r,
                      backgroundImage: AssetImage(friend.avatar ?? ''),
                    ),
                    SizedBox(width: 12.w),

                    // 好友信息
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            friend.nickname ?? friend.username,
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16.sp,
                              color: Colors.black,
                            ),
                          ),
                          SizedBox(height: 4.h),
                          Text(
                            friend.signature ?? 'No signature',
                            style: TextStyle(
                              color: Colors.grey,
                              fontSize: 14.sp,
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ],
                      ),
                    ),

                    // 删除按钮
                    GestureDetector(
                      onTap: () {
                        showAwakDialog(
                          context: context,
                          title: 'DELETE FRIEND',
                          description: 'Are you sure you want to delete this friend?',
                          onConfirm: () {
                            final currentUser = context.read<AwakBloc>().userRepository.currentUser;
                            if (currentUser != null) {
                              context.read<AwakBloc>().add(
                                RemoveFriendEvent(currentUser.id!, friend.id!)
                              );
                            }
                          },
                          onCancel: () {},
                        );
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                        decoration: BoxDecoration(
                          color: Colors.transparent,
                          borderRadius: BorderRadius.circular(4.r),
                          border: Border.all(color: Colors.grey),
                        ),
                        child: Text(
                          'Delete',
                          style: TextStyle(
                            color: Colors.grey,
                            fontSize: 12.sp,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              );
            },
          );
        }

        // 如果状态不是 FriendsLoaded，尝试重新加载好友列表
        if (state is! FriendsLoaded && state is! FriendshipLoading) {
          // 延迟重新加载，避免无限循环
          WidgetsBinding.instance.addPostFrameCallback((_) {
            final currentUser = context.read<AwakBloc>().userRepository.currentUser;
            if (currentUser != null) {
              context.read<AwakBloc>().add(FetchFriendsEvent(currentUser.id!));
            }
          });
        }

        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'Loading friend list...',
                style: TextStyle(
                  color: Colors.grey,
                  fontSize: 16.sp,
                ),
              ),
              SizedBox(height: 16.h),
              CircularProgressIndicator(),
            ],
          ),
        );
      },
    );
  }

  Widget _buildUnreadBadge(int userId) {
    final unreadCount = _unreadCounts[userId] ?? 0;

    if (unreadCount == 0) {
      return const SizedBox.shrink();
    }

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
      decoration: const BoxDecoration(
        color: Color(0xFFD3F524),
        shape: BoxShape.circle,
      ),
      constraints: BoxConstraints(
        minWidth: 20.w,
        minHeight: 20.h,
      ),
      child: Center(
        child: Text(
          unreadCount > 99 ? '99+' : unreadCount.toString(),
          style: TextStyle(
            color: Colors.black,
            fontSize: 12.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
}